#include <napi/native_api.h>
#include "BlankDetector.h"
#include <hilog/log.h>

#undef LOG_DOMAIN
#undef LOG_TAG
#define LOG_DOMAIN 0x3200
#define LOG_TAG "BlankDetector"

static napi_value DetectBlankRegions(napi_env env, napi_callback_info info) {
    size_t argc = 4;
    napi_value args[4];
    napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
    
    if (argc < 3) {
        napi_throw_error(env, nullptr, "Expected at least 3 arguments: ArrayBuffer, width, height");
        return nullptr;
    }
    
    // 获取ArrayBuffer
    void* pixelData = nullptr;
    size_t byteLength = 0;
    napi_status status = napi_get_arraybuffer_info(env, args[0], &pixelData, &byteLength);
    if (status != napi_ok || !pixelData) {
        napi_throw_error(env, nullptr, "Failed to get ArrayBuffer data");
        return nullptr;
    }
    
    // 获取宽度
    int32_t width;
    status = napi_get_value_int32(env, args[1], &width);
    if (status != napi_ok || width <= 0) {
        napi_throw_error(env, nullptr, "Invalid width parameter");
        return nullptr;
    }
    
    // 获取高度
    int32_t height;
    status = napi_get_value_int32(env, args[2], &height);
    if (status != napi_ok || height <= 0) {
        napi_throw_error(env, nullptr, "Invalid height parameter");
        return nullptr;
    }
    
    // 获取每像素字节数（可选，默认为4）
    int32_t bytesPerPixel = 4;
    if (argc >= 4) {
        status = napi_get_value_int32(env, args[3], &bytesPerPixel);
        if (status != napi_ok || bytesPerPixel <= 0) {
            bytesPerPixel = 4; // 默认RGBA
        }
    }
    
    // 验证数据大小
    size_t expectedSize = width * height * bytesPerPixel;
    if (byteLength < expectedSize) {
        OH_LOG_ERROR(LOG_APP, "ArrayBuffer size mismatch: expected %{public}zu, got %{public}zu", 
                     expectedSize, byteLength);
        napi_throw_error(env, nullptr, "ArrayBuffer size does not match image dimensions");
        return nullptr;
    }
    
    OH_LOG_INFO(LOG_APP, "Starting blank detection: %{public}dx%{public}d, %{public}d bytes per pixel", 
                width, height, bytesPerPixel);
    
    // 执行检测
    DetectionResult result = BlankDetector::detect(
        static_cast<const uint8_t*>(pixelData),
        width, height, bytesPerPixel
    );
    
    OH_LOG_INFO(LOG_APP, "Detection completed: level=%{public}d, ratio=%{public}f", 
                static_cast<int>(result.blankLevel), result.totalBlankRatio);
    
    // 创建返回对象
    napi_value resultObj;
    napi_create_object(env, &resultObj);
    
    // 设置空白等级
    napi_value blankLevel;
    napi_create_int32(env, static_cast<int>(result.blankLevel), &blankLevel);
    napi_set_named_property(env, resultObj, "blankLevel", blankLevel);
    
    // 设置空白比例
    napi_value totalBlankRatio;
    napi_create_double(env, result.totalBlankRatio, &totalBlankRatio);
    napi_set_named_property(env, resultObj, "totalBlankRatio", totalBlankRatio);
    
    // 设置最大区域大小
    napi_value largestRegionSize;
    napi_create_int32(env, result.largestRegionSize, &largestRegionSize);
    napi_set_named_property(env, resultObj, "largestRegionSize", largestRegionSize);
    
    // 设置区域数量
    napi_value regionCount;
    napi_create_int32(env, static_cast<int>(result.blankRegions.size()), &regionCount);
    napi_set_named_property(env, resultObj, "regionCount", regionCount);
    
    // 设置描述
    napi_value description;
    napi_create_string_utf8(env, result.description.c_str(), NAPI_AUTO_LENGTH, &description);
    napi_set_named_property(env, resultObj, "description", description);
    
    return resultObj;
}

EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports) {
    napi_property_descriptor desc[] = {
        {
        "detectBlankRegions",
        nullptr,
        DetectBlankRegions,
        nullptr,
        nullptr,
        nullptr,
        napi_default,
        nullptr
        }
    };
    
    napi_define_properties(env, exports, sizeof(desc)/sizeof(desc[0]), desc);
    return exports;
}
EXTERN_C_END

static napi_module demoModule = {
    .nm_version = 1,
    .nm_flags = 0,
    .nm_filename = nullptr,
    .nm_register_func = Init,
    .nm_modname = "entry",
    .nm_priv = ((void*)0),
    .reserved = { 0 },
};

extern "C" __attribute__((constructor)) void RegisterBlankDetectorModule(void) {
    napi_module_register(&demoModule);
}